package com.git.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.git.domain.UserEntity;
import com.git.mapper.UserDao;

/**
 * 一个自定义的service用来和数据库进行操作. 即以后我们要通过数据库保存权限.则需要我们继承UserDetailsService
 * 总结：
 *    1.security.xml就好像是一个controller，登陆页面提交后，就到security.xml，然后再调用这个service来获得UserDetails对象
 * 
 */
public class CustomUserDetailsService implements UserDetailsService {
	private UserDao userDAO = new UserDao();
	
	/** 
	 * 验证用户信息的方法
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		//先按照用户名找到用户对象
		UserEntity userEntity = userDAO.getDatabase(username);
		//把用户的：用户名、密码、级别，都交给UserEntity对象。
		UserDetails userDetails = null;
		if (userEntity != null) {
			userDetails = new User(userEntity.getUsername(), userEntity.getPassword(), this.getAuthorities(userEntity.getAccess()));
		} else {
			throw new UsernameNotFoundException("没有找到该用户");
		}
		return userDetails;
	}

	/**
	 * 把access转化成权限集合对象
	 */
	public Collection<GrantedAuthority> getAuthorities(Integer access) {
//		把该用户拥有的权限都放到这个列表中
		List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(2);
		
		// 首先放入ROLE_USER权限
		list.add(new GrantedAuthorityImpl("ROLE_USER"));

		// 如果参数access为1.则拥有ROLE_ADMIN权限
		if (access.compareTo(1) == 0) {
			list.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		}

		return list;
	}
}
